package io.zhengsh.br2.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class GoodsController {

    private final String REDIS_LOCK = "good_lock";

    private Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${server.port}")
    private Integer serverPort;

    @Autowired
    private Redisson redisson;

    @GetMapping("/buyGoods")
    public String buyGoods() {
        RLock rLock = redisson.getLock(REDIS_LOCK);
        rLock.lock();
        try {
            String result = stringRedisTemplate.opsForValue().get("goods:001");
            int goodsNumber = result == null ? 0 : Integer.valueOf(result);
            if (goodsNumber > 0) {
                int realNumber = goodsNumber - 1;
                stringRedisTemplate.opsForValue().set("goods:001", String.valueOf(realNumber));
                logger.info("成功买到商品， 库存还剩下：{} 件｜服务提供者 serverPort : {}", realNumber, serverPort);


                return "成功买到商品， 库存还剩下：" + realNumber + " 件｜服务提供者 serverPort : " + serverPort;
            }
            logger.info("商品已经售完/活动结束/调用超时, 欢迎下次光临, serverPort:{}", serverPort);
            return "商品已经售完/活动结束/调用超时, 欢迎下次光临, serverPort:" + serverPort;
        } finally {
            if (rLock.isLocked() && rLock.isHeldByCurrentThread()) {
                rLock.unlock();
            }
        }
    }
}
